//
//  ExamQuestionsListCell.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/3.
//

#import "ExamQuestionsListCell.h"

@interface ExamQuestionsListCell()

@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIImageView *errorImageView;
@property(nonatomic,strong)UIImageView *contentImageView;


@end

@implementation ExamQuestionsListCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    __weak typeof(self)self_weak_ = self;
    self.backgroundColor = UIColorHex(0xF2F7F6);
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.bgView = [[UIView alloc]init];
    self.bgView.backgroundColor = [UIColor whiteColor];
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
    [self.contentView addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(@10);
        make.bottom.mas_equalTo(@-10);
    }];
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.font = JPUIFontInterMedium(16);
    self.countLabel.textColor = KFontBlackColor;
    [self.bgView addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.height.mas_equalTo(@19);
        make.centerY.mas_equalTo(self_weak_.bgView);
    }];
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontPingFangSCRegular(16);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.numberOfLines = 0;
    [self.bgView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@47);
        make.centerY.mas_equalTo(self_weak_.bgView);
        make.right.mas_equalTo(@-16);
    }];
    
    self.contentImageView = [[UIImageView alloc]init];
    self.contentImageView.backgroundColor = [UIColor whiteColor];
    [self.bgView addSubview:self.contentImageView];
    [self.contentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@47);
        make.centerY.mas_equalTo(self_weak_.bgView);
        make.width.height.mas_equalTo(@0);
    }];
    self.contentImageView.hidden = YES;
    
    self.errorImageView = [[UIImageView alloc]init];
    self.errorImageView.image = [UIImage imageNamed:@"exam_question_error"];
    [self.bgView addSubview:self.errorImageView];
    [self.errorImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@20);
        make.centerY.mas_equalTo(self_weak_.bgView);
        make.right.mas_equalTo(@-16);
    }];
    self.errorImageView.hidden = YES;
}

-(void)setType:(NSInteger)type{
    _type = type;
    if(type == 2){
        //正确
        self.bgView.backgroundColor = KThemeColor;
        self.titleLabel.textColor = [UIColor whiteColor];
        self.contentImageView.backgroundColor = KThemeColor;
        self.countLabel.textColor = [UIColor whiteColor];
        self.errorImageView.hidden = YES;
        self.bgView.layer.borderWidth = 0;
        self.bgView.layer.borderColor = KThemeColor.CGColor;
        [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(@-16);
        }];
    }else{
        self.bgView.backgroundColor = [UIColor whiteColor];
        self.contentImageView.backgroundColor = [UIColor whiteColor];
        self.titleLabel.textColor = KFontBlackColor;
        self.countLabel.textColor = KFontBlackColor;
        if(type == 3){
            //错误
            self.errorImageView.hidden = NO;
            self.bgView.layer.borderWidth = 0;
            self.bgView.layer.borderColor = [UIColor whiteColor].CGColor;
            [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-32-20);
            }];
            
        }else{
            self.errorImageView.hidden = YES;
            if(type == 1){
                //选中
                self.bgView.layer.borderWidth = 1;
                self.bgView.layer.borderColor = UIColorHex(0x868F99).CGColor;
            }else{
                //正常
                self.bgView.layer.borderWidth = 0;
                self.bgView.layer.borderColor = [UIColor whiteColor].CGColor;
            }
            [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-16);
            }];
        }
    }
}

//-(void)setRow:(NSInteger)row{
//    _row = row;
//    self.countLabel.text = [NSString stringWithFormat:@"%ld",row+1];
//}

-(void)setModel:(ExamQuestionOptionsModel *)model{
    _model = model;
    self.countLabel.text = model.optionKey;
    if(model.optionValue&&[model.optionValue containsString:@"<img src="]){
        //图片
        self.contentImageView.hidden = NO;
        self.titleLabel.hidden = YES;
        NSArray *arr = [self extractImageInfoFromHTMLString:model.optionValue];
        if(arr.count == 3){
            NSString *path = arr[0];
            NSString *pic_w = arr[1];
            NSString *pic_h = arr[2];
            CGFloat max_w = self.currentAvailableWidth-32-16-47;
            if(_type == 3){
                //显示错误时
                max_w = self.currentAvailableWidth-32-32-47-20;
            }
            CGFloat w = pic_w.floatValue;
            CGFloat h = pic_h.floatValue;
            if(w > max_w){
                w = max_w;
                h = w*pic_h.floatValue/pic_w.floatValue;
            }
            [self.contentImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(w);
                make.height.mas_equalTo(h);
                if(_type == 3){
                    make.right.mas_equalTo(-32-20);
                }else{
                    make.right.mas_equalTo(@-16);
                }
            }];
            [self.contentImageView sd_setImageWithURL:[NSURL URLWithString:path]];
        }
    }else{
        self.contentImageView.hidden = YES;
        self.titleLabel.hidden = NO;
        self.titleLabel.attributedText = [self parseHTMLString:model.optionValue?model.optionValue:@"" withFont:self.titleLabel.font color:self.titleLabel.textColor];
    }
}

#pragma mark - 取出图片数据
- (NSArray *)extractImageInfoFromHTMLString:(NSString *)htmlString{
    NSMutableArray *resultArray = [NSMutableArray arrayWithObjects:@"", @"0", @"0", nil];
    NSString *pattern = @"<img[^>]+src\\s*=\\s*\"([^\"]+)\"[^>]*width\\s*=\\s*\"(\\d+)\"[^>]*height\\s*=\\s*\"(\\d+)\"";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return resultArray;
    }
    
    NSTextCheckingResult *match = [regex firstMatchInString:htmlString options:0 range:NSMakeRange(0, [htmlString length])];
    if (match) {
        if ([match rangeAtIndex:1].location != NSNotFound) {
            NSString *url = [htmlString substringWithRange:[match rangeAtIndex:1]];
            resultArray[0] = url ? url : @"";
        }
        
        if ([match rangeAtIndex:2].location != NSNotFound) {
            NSString *width = [htmlString substringWithRange:[match rangeAtIndex:2]];
            resultArray[1] = width ? width : @"0";
        }
        
        if ([match rangeAtIndex:3].location != NSNotFound) {
            NSString *height = [htmlString substringWithRange:[match rangeAtIndex:3]];
            resultArray[2] = height ? height : @"0";
        }
    }
    
    return resultArray;
}


#pragma mark - 处理富文本划线
- (NSAttributedString *)parseHTMLString:(NSString *)htmlString withFont:(UIFont *)font color:(UIColor *)color {
    // 1. 处理转义字符
    NSString *unescapedHTMLString = [self unescapeHTMLString:htmlString];
    // 2. 创建 NSMutableAttributedString
    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] init];
    // 3. 正则表达式，匹配带有下划线的部分
    NSString *pattern = @"<span style=\"text-decoration: underline;\">(.*?)</span>";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return [[NSAttributedString alloc] initWithString:htmlString attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: color}];
    }
    __block NSUInteger lastLocation = 0;
    
    // 4. 设置段落样式为按字符换行
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;  // 设置按字符换行
    
    NSDictionary *normalAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle};
    NSDictionary *underlineAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), NSParagraphStyleAttributeName: paragraphStyle};
    
    // 5. 处理匹配的文本
    [regex enumerateMatchesInString:unescapedHTMLString options:0 range:NSMakeRange(0, unescapedHTMLString.length) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
        // 处理普通文本部分
        if (match.range.location > lastLocation) {
            NSString *normalText = [unescapedHTMLString substringWithRange:NSMakeRange(lastLocation, match.range.location - lastLocation)];
            normalText = [self stripHTMLTags:normalText];
            NSMutableAttributedString *normalAttributedString = [[NSMutableAttributedString alloc] initWithString:normalText attributes:normalAttributes];
            [resultString appendAttributedString:normalAttributedString];
        }
        
        // 处理下划线文本部分
        NSRange underlineRange = [match rangeAtIndex:1];
        NSString *underlineText = [unescapedHTMLString substringWithRange:underlineRange];
        NSMutableAttributedString *underlinedAttributedString = [[NSMutableAttributedString alloc] initWithString:underlineText attributes:underlineAttributes];
        [resultString appendAttributedString:underlinedAttributedString];
        
        lastLocation = match.range.location + match.range.length;
    }];
    
    // 处理剩余的普通文本部分
    if (lastLocation < unescapedHTMLString.length) {
        NSString *remainingText = [unescapedHTMLString substringFromIndex:lastLocation];
        remainingText = [self stripHTMLTags:remainingText];
        NSMutableAttributedString *remainingAttributedString = [[NSMutableAttributedString alloc] initWithString:remainingText attributes:normalAttributes];
        [resultString appendAttributedString:remainingAttributedString];
    }
    
    return resultString;
}


// 移除 HTML 标签的辅助方法
- (NSString *)stripHTMLTags:(NSString *)htmlString {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<[^>]+>" options:0 error:nil];
    NSString *cleanedString = [regex stringByReplacingMatchesInString:htmlString options:0 range:NSMakeRange(0, htmlString.length) withTemplate:@""];
    return cleanedString;
}

// 恢复 HTML 转义字符的辅助方法
- (NSString *)unescapeHTMLString:(NSString *)htmlString {
    NSString *unescapedString = [htmlString stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
    return unescapedString;
}


- (void)animateBgViewWithCompletion:(void (^)(void))completion{
    self.type = 1;
    [UIView animateWithDuration:0.05
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.bgView.transform = CGAffineTransformMakeScale(1.1, 1.1);
                     }
                     completion:^(BOOL finished) {
                         [UIView animateWithDuration:0.05
                                               delay:0
                                             options:UIViewAnimationOptionCurveEaseInOut
                                          animations:^{
                                              self.bgView.transform = CGAffineTransformMakeScale(0.95, 0.95);
                                          }
                                          completion:^(BOOL finished) {
                                              [UIView animateWithDuration:0.05
                                                                    delay:0
                                                                  options:UIViewAnimationOptionCurveEaseInOut
                                                               animations:^{
                                                                   self.bgView.transform = CGAffineTransformIdentity;
                                                               }
                                                               completion:^(BOOL finished) {
                                                                   if (completion) {
                                                                       completion();
                                                                   }
                                                               }];
                                          }];
                     }];
}


@end
